import json

from django.http import JsonResponse
from django.views import View
from app.models import *
from app.url import *
from app.respositories.respositories import consumer_coins


# 获取首页卡片信息
class HomeView(View):
    def get(self, request):
        try:
            # 获取所随机10个用户数据并返回
            user = User.objects.select_related('userinfo').all().order_by('?')[:10]
            # 转换为字典列表并返回
            data = []
            for u in user:
                data.append({
                    'id': u.id,
                    'nickname': u.userinfo.nickname,
                    'avatar': get_server_url(request) + u.userinfo.avatar,
                    'gender': u.userinfo.gender,
                    'age': u.userinfo.age,
                    'household_region': u.userinfo.housing_status,
                    'marital_status': u.userinfo.marital_status,
                    'height': u.userinfo.height,
                    'occupation': u.userinfo.occupation,
                    'education': u.userinfo.education,
                    'monthly_income': u.userinfo.monthly_income,
                    'hobbies': u.userinfo.hobbies,
                    'self_introduction': u.userinfo.self_introduction,
                    'ask': {
                        'age_range': u.userinfo.age_range,
                        'height_range': u.userinfo.height_range,
                        'desired_marital_status': u.userinfo.desired_marital_status,
                        'minimum_education': u.userinfo.minimum_education,
                        'minimum_income': u.userinfo.minimum_income,
                        'marriage_timing': u.userinfo.marriage_timing,
                        'desired_work_region': u.userinfo.my_city,
                        'desired_housing_status': u.userinfo.desired_housing_status,
                        'other_requirements': u.userinfo.other_requirements
                    }
                })
            # 转换为字典列表并返回
            return JsonResponse({
                'code': 200,
                'msg': '获取成功',
                'data': {
                    'result': data
                },
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': str(e)
            })


# 获取首页轮播图
class HomeBannerView(View):
    def get(self, request):
        try:
            # 获取所有轮播图数据并返回
            banner = Banner.objects.all()
            # 转换为字典列表并返回
            data = []
            for b in banner:
                data.append({
                    'id': b.id,  # 轮播图id
                    'imgUrl': get_server_url(request) + b.imgUrl,  # 轮播图地址
                    "hrefUrl": b.hrefUrl  # 轮播图链接
                })
            return JsonResponse({
                'code': 200,  # 状态码
                'data': {
                    "result": data
                },  # 轮播图数据
                'msg': '请求成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': str(e)
            })


# 获取首页分类信息
class HomeCategoryView(View):
    def get(self, request):
        try:
            # 获取所有分类数据并返回
            category = NavButton.objects.all()
            # 转换为字典列表并返回
            data = []
            for c in category:
                data.append({
                    'id': c.id,  # 分类id
                    'icon': get_server_url(request) + c.iconPath,  # 分类图标
                    'title': c.title,  # 分类名称
                    "pageStatus": c.pageStatus,
                    'route': c.route
                })
            return JsonResponse({
                'code': 200,  # 状态码
                'data': {
                    'result': data
                },  # 分类数据
                'msg': '请求成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': str(e)
            })


# 获取首页置顶嘉宾信息
class HomeTopUpView(View):
    def get(self, request):
       try:
            # 获取随机用户
            users = UserTop.objects.select_related('user').select_related('user__userinfo').all().order_by('?')[:3]
            # 转换为字典列表并返回
            data = []
            for u in users:
                data.append({
                    'id': u.user.id,  # 置顶用户id
                    'nickname': u.user.userinfo.nickname,  # 置顶用户称
                    'avatar': get_server_url(request) + u.user.userinfo.avatar,  # 置顶用户头像
                    'my_city': u.user.userinfo.my_city,  # 置顶用户城市
                    'age': u.user.userinfo.age  # 用户年龄
                })

            return JsonResponse({
                'code': 200,  # 状态码
                'data': {
                    'result': data
                },  # 置顶用户数据
                'msg': '请求成功'
            })
       except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': str(e)
            })

    # 用户置顶
    def post(self, request):
        try:
            # 获取用户id
            u_id = request.POST.get('u_id', '')
            moneys = User.objects.select_related('gold').get(id=u_id)
            istop = UserTop.objects.filter(user__id=u_id)
            if len(istop) > 0:
                return JsonResponse({
                    'code': 200,
                    'msg': '您已置顶'
                })
            # 扣除金币
            if moneys.gold.money >= 50:
                # 从金币表中扣除
                g = Gold.objects.get(id=u_id)
                # 记录置顶前的金币
                g.money = moneys.gold.money - 50
                # 保存
                g.save()
                # 记录消费记录
                consumer_coins({
                    'user_id': u_id,
                    'limit': 50,
                    'msg': '置顶花费'
                })
                # 创建置顶记录
                UserTop.objects.create(user_id=u_id, id=uuid.uuid4())
                # 置顶并返回
                return JsonResponse({
                    'code': 200,
                    'msg': '置顶'
                })
            else:
                return JsonResponse({
                    'code': 400,
                    'msg': '金币不足'
                })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'置顶失败 err({e})'
            })


class AvatarView(View):
    def get(self, request):
        try:
            # 获取头像
            u_id = request.GET.get('u_id', '')
            print(u_id, '11')
            # 读取头像并返回
            avatar = User.objects.get(id=u_id)
            print(u_id)
            return JsonResponse({
                'code': 200,
                'data': {
                    'avatar': get_server_url(request),
                    'url': avatar.userinfo.avatar
                },
            })  # 头像返回为 JPEG格式
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'读取头像失败：{str(e)}'
            })
